// pages/product/productinfo/productinfo.js

const App = getApp()
let { AJAX, productKind, formatRichText, timeTranfer,imgUrl } = require('../../../utils/util.js')
Page({  
  
   /**
    * 页面的初始数据  
    */ 
   data: {  
      proid: '', 
      navH: '',
      dataInfo: {},
      activeNum: 'point',
      tabPosition: false, 
      scrolltop: 0, 
      chooseSize: false, 
      chooseSize1: false, 
      animationData: {}, 
      selected: 0,
      list: [],
      timeList: [],
      selected_time: 0,
      priceType: 0,
      priceTime: 0,
      dateTitle: '请选择出行时间',
      click_time: 0,
      sale_price: 0,
      /**2.0 */
      isAuth: false,
      is_share: true,
      share_member_id: 0,
      userName: '',
      myId: '',
      fenxiangzhe: '',
      showVideo: false,
      level:'',
      is_code:false,
      firsrCodeUrl:'',
      codeUrl:'',
      showpost:false,
      scene:'',
      file_name:'',
      product_price:true,
      floorstatus: false, 
     imgUrl: imgUrl

     
   },

   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
   
      let vm = this
   
      if (options.scene) {
         let scene = decodeURIComponent(options.scene);
         let proid = scene.split("&")[0];
         let share_member_id = scene.split('&')[1];
         this.setData({
            proid: proid,
            share_member_id: share_member_id,
         })
        
      }else{
         this.setData({
           proid: options.id,           
        })
      }
      this.setData({
         navH: App.globalData.navHeight,
        
      })
    

      if (!wx.getStorageSync("ACCESSTOKEN")) {
         getApp().userInfoReadyCallback = res => {
            wx.setStorageSync('ACCESSTOKEN', res);
            vm.requestInfo()
            vm.getUserInfo()
            vm.is_share_member_id()
            vm.requestAuch()
            
         }
         return
      }
      vm.requestInfo()
      vm.getUserInfo()
      vm.is_share_member_id()
      vm.requestAuch()
    
      //this.getHaiBao()
     
   },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function () {

   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function () {
      // this.requestInfo()
      this.requestAuch()
   },

   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide: function () {

   },

   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function () {

   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {

   },

   /**
    * 页面上拉触底事件的处理函数
    */
   onReachBottom: function () {

   },

   /**
    * 用户点击右上角分享
    */
    
   onShareAppMessage: function (res) {   
      let that = this;
      if (!that.data.isAuth) {
         return wx.navigateTo({
            url: '/pages/authorization/authorization',
         })
       
      } else {
         if (res.from === "button") {
            return {
               title: this.data.userName + '给您分享了:' + this.data.dataInfo.product_name,
               path: '/pages/product/productinfo/productinfo?id=' + this.data.dataInfo.product_id + "&share_member_id=" + this.data.myId // 路径，传递参数到指定页面。
            }

         } else if (res.from === "menu") {
            return {
               title: this.data.userName + '给您分享了:' + this.data.dataInfo.product_name,
               path: '/pages/product/productinfo/productinfo?id=' + this.data.dataInfo.product_id + "&share_member_id=" + this.data.myId // 路径，传递参数到指定页面。
            }
         }
      }
     
     
   },

   /**
    * 小程序2.0
    */
   checkBtn() {
      this.setData({
         is_share: true
      })
     
   },
   
  

   // 判断点击分享进来
   //share_member_id
   is_share_member_id() { 
      let num = this.data.share_member_id    
     
      if (this.data.share_member_id != 0 && this.data.share_member_id != undefined) {         
         this.setData({
            is_share: false
         })         
         AJAX('member/member-info', 'GET', {
            member_id: this.data.share_member_id
         }).then(res => { 
         
            this.setData({
               fenxiangzhe: res.data,
            })
         })
         AJAX('share-product/share', 'POST', {
            share_member_id: this.data.share_member_id,
            product_id: this.data.proid
         }).then(res => { })
      } 
   },
   /**
    * 用户id
    * member/member-info
    */
   getUserInfo() {
      let num = this.data.share_member_id     
      AJAX('member/member-info', 'GET').then(res => {  
            
         this.setData({
           level: res.data.level,
            userName: res.data.username,
            myId: res.data.member_id
         })
      })
    
   },


 

   /**
    * 小程序1.1
    */
   // 时间选择
   selected_time_click: function (e) {

      let that = this
      let index = e.currentTarget.dataset.index;
      let item = e.currentTarget.dataset.item;

      that.setData({
         selected_time: e.currentTarget.dataset.index,
         priceTime: item.timetable_id
      })

   },
   //tab框
   selected: function (e) {

      let that = this
      let index = e.currentTarget.dataset.index;


      that.setData({
         selected: e.currentTarget.dataset.index,
         priceTime: that.__data__.dataInfo.productSchedule[index].timeTable[0].timetable_id,
         priceType: that.__data__.dataInfo.productSchedule[index].schedule_title,
         sale_price: that.__data__.dataInfo.productSchedule[index].sales_price,
         product_price: false
      })

   },

   // 弹窗
   chooseSezi1: function (e) {
      // 用that取代this，防止不必要的情况发生

      var that = this;
      // 创建一个动画实例
      var animation = wx.createAnimation({
         // 动画持续时间
         duration: 500,
         // 定义动画效果，当前是匀速
         timingFunction: 'linear'
      })
      // 将该变量赋值给当前动画
      that.animation = animation
      // 先在y轴偏移，然后用step()完成一个动画
      animation.translateY(200).step()
      // 用setData改变当前动画
      that.setData({
         // 通过export()方法导出数据
         animationData: animation.export(),
         // 改变view里面的Wx：if
         chooseSize1: true,
         click_time: 1,

      })
      // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
      setTimeout(function () {
         animation.translateY(0).step()
         that.setData({
            animationData: animation.export()
         })
      }, 200)
   },
   chooseSezi: function (e) {
      // 用that取代this，防止不必要的情况发生

      var that = this;
      // 创建一个动画实例
      var animation = wx.createAnimation({
         // 动画持续时间
         duration: 500,
         // 定义动画效果，当前是匀速
         timingFunction: 'linear'
      })
      // 将该变量赋值给当前动画
      that.animation = animation
      // 先在y轴偏移，然后用step()完成一个动画
      animation.translateY(200).step()
      // 用setData改变当前动画
      that.setData({
         // 通过export()方法导出数据
         animationData: animation.export(),
         // 改变view里面的Wx：if
         chooseSize: true
      })
      // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
      setTimeout(function () {
         animation.translateY(0).step()
         that.setData({
            animationData: animation.export()
         })
      }, 200)
   },
   // 关闭弹窗
   hideModal: function (e) {
      var that = this;
      let type = e.currentTarget.dataset.type;

      var animation = wx.createAnimation({
         duration: 1000,
         timingFunction: 'linear'
      })
      that.animation = animation
      animation.translateY(200).step()
      that.setData({
         animationData: animation.export(),
         product_price: false

      })
      setTimeout(function () {
         animation.translateY(0).step();
         that.setData({
            animationData: animation.export(),
            chooseSize: false,
            chooseSize1: false,

         });
         if (type == 'coupon' && that.data.priceType == 0) {

            that.setData({
               dateTitle: that.data.dateTitle,
               
              
            })
         } else {
            that.setData({
               dateTitle: that.data.priceType,
            })
         }
      }, 200)
   },
   // 关闭弹窗获取数据
   returnData: function () {
      let that = this;
      if (!that.data.isAuth) {
         return wx.navigateTo({
            url: '/pages/authorization/authorization',
         })
      } else {
         that.setData({
            chooseSize1: false
         })
         wx.navigateTo({
            url: '/pages/order/orderwrite/orderwrite?id=' + this.data.proid + "&timeable_id=" + this.data.priceTime,
         }) 
       
      }

   },
   mianfei(){
      wx.navigateTo({
         url: '/pages/order/peserve/reserve?id=' + this.data.proid + "&timeable_id=" + this.data.priceTime,
      })  
   },
   // 获取详情
   move() { },
   requestInfo() {
      let vm = this
      AJAX("product/info", "GET", {
         id: vm.data.proid
      }).then(res => {
         let item = res.data
         // 保存商品列表
         let _list = []
         item.productSchedule.forEach((val, index) => {

            _list.push(val.schedule_title)
         })
         res.data.pre_sales = parseInt(res.data.total_sales) + parseInt(res.data.pre_sales)
         // 返利数值int
        
         res.data.rake_back.two_level_profit = parseInt(res.data.rake_back.two_level_profit)
         res.data.rake_back.one_level_profit = parseInt(res.data.rake_back.one_level_profit)

         // 更改选择时间的时间戳        
         item.productSchedule.forEach((val, index) => {

            val.timeTable.forEach((v, index) => {
               v.timetable_time = timeTranfer(v.timetable_time, 1)
            })

         })
         // 更改时间戳
         item.coupons.forEach((val, index) => {
            val.created_at = timeTranfer(val.created_at, 1)
            val.start_time = timeTranfer(val.start_time, 1)
            val.end_time = timeTranfer(val.end_time, 1)
            val.price = parseInt(val.price)
            val.floor_price = parseInt(val.floor_price)
         })
         item.product_kind = productKind[item.product_kind || 1]
         item.theme_name = item.theme_name
         // console.log(item.productSchedule[0].sales_price)
         if (item.theme_name) {
            item.theme_name = item.theme_name.split('|')
         }
         if (item.productTrip) {
            item.productTrip.forEach(function (it, index) {
               item.productTrip[index].trip_content = formatRichText(it.trip_content).replace(/<section/g, '<div')
                  .replace(/\/section>/g, '\div>');
            })
         }
         // 费用包含 dataInfo.productDetails.cost_list
         item.productDetails.cost_list = formatRichText(item.productDetails.cost_list).replace(/<section/g, '<div').replace(/\/section>/g, '\div>')
         item.productDetails.about_us = formatRichText(item.productDetails.about_us).replace(/<section/g, '<div').replace(/\/section>/g, '\div>')
         item.productDetails.notice = formatRichText(item.productDetails.notice).replace(/<section/g, '<div').replace(/\/section>/g, '\div>')

         if (item.productPoint) {
            item.productPoint.forEach(function (it, index) {
               item.productPoint[index].point_content = formatRichText(it.point_content).replace(/<section/g, '<div')
                  .replace(/\/section>/g, '\div>');
            })
         }
         if (item.begin_time) {
            item.begin_time = timeTranfer(item.begin_time, 1)
         }
         if (item.productCategory.product_type == 1) {
            vm.setData({
               dateTitle: '请选择课时'
            })
         }
     
         vm.setData({
            dataInfo: item,
            sale_price: item.productSchedule[0].sales_price,
            priceType: item.productSchedule[0].schedule_title,
            priceTime: item.productSchedule[0].timeTable[0].timetable_id,
            list: _list
         })         
         if (item.product_poster!=''){
            AJAX('qrcode/qrcode', 'POST', {
               url: 'pages/product/productinfo/productinfo',
               poster_url: vm.data.dataInfo.product_poster,
               scene: vm.data.proid + "&" + vm.data.myId,
               type: "haibao"
            }).then(res => {
             
               vm.setData({
                  firsrCodeUrl:res.data.img,
                  file_name: res.data.file_name,
                  is_code: true
               })
               
            }) 

         }       
      })
   },  
 
   getSharePoster: function () {  
      wx.showToast({
         title: '加载中...',
         mask: true,
         duration:500,
         icon: 'loading'
      })
      let that = this;
      if (!that.data.isAuth) {
         wx.navigateTo({
            url: '/pages/authorization/authorization',
         })
         return false
      } else {
         this.setData({ showpost: true })
         if (this.data.is_code == false) {
          
            AJAX('qrcode/qrcode', 'POST', {
               url: 'pages/product/productinfo/productinfo',
               poster_url: this.data.dataInfo.product_poster,
               scene: this.data.proid + "&" + this.data.myId,
               type: "haibao"
            }).then(res => {                       
               this.setData({
                  codeUrl: res.data.img,
                  file_name: res.data.file_name
               })

            })  
         }
        
      }
   },
  
   closePoste: function () {
      this.setData({
         showpost: false
      })
   },

   saveShareImg: function () {
      var that = this;
      wx.showLoading({
         title: '正在保存',
         mask: true,
      })
      let imgSRc = this.data.firsrCodeUrl || this.data.codeUrl 
      setTimeout(function () {
         wx.downloadFile({
            url: imgSRc,
            success: function (res) {
          
               //图片保存到本地
               wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function (data) {
                     wx.showToast({
                        title: '保存成功',
                        icon: 'success',
                        duration: 2000
                     })                   
                    
                     // 下载成功后删除二维码qrcode/del-image
                     AJAX('qrcode/del-image', 'POST', {
                        file_name: that.data.file_name
                     }).then(res => {
                       
                        console.log("删除成功")
                     })
                  },
                  fail: function (res) {
                     if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {                     
                        wx.showToast({
                           title: '保存图片失败，您已取消保存图片到相册',
                           icon: 'success',
                           duration: 2000
                        })
                     } else {
                        wx.showModal({
                           title: '提示',
                           content: '保存图片失败，您可以点击确定设置获取相册权限后再尝试保存！',
                           complete: function (res) {
                              console.log(res);
                              if (res.confirm) {
                                 wx.openSetting({}) //打开小程序设置页面，可以设置权限
                              } else {
                                 wx.showToast({
                                    title: '保存图片失败，您已取消保存图片到相册',
                                    icon: 'success',
                                    duration: 2000
                                 })
                              }
                           }
                        });
                     }
                  },
                  complete(res) {
                     console.log(res);
                  }
               })
            }
         })
      
      }, 1000);
   },





   // 领取优惠券
   receive(e) {

      AJAX('coupon-member/receive-coupon', 'POST', {
         coupon_id: e.currentTarget.dataset.id
      }).then(res => {
         if (res.status == 'succeed') {
            console.log("领取成功")
            wx.showToast({
               title: '领取成功',
               icon: "none"
            })

            //刷新当前页面的数据
            wx: wx.navigateTo({
               url: '/pages/product/productinfo/productinfo?id=' + this.data.proid,
               // success: function(res) {},
               // fail: function(res) {},
               // complete: function(res) {},
            })
         }


      })
   },
   tabActive(e) {
      let _type = e.currentTarget.dataset.type
      //consoe.log(_type)
      this.setData({
         activeNum: _type
      })
   },
   makePhone(e) {
      let _phone = e.currentTarget.dataset.phone
      if (!_phone) {
         return
      }
      wx.makePhoneCall({
         phoneNumber: _phone,
      })
   },
   writeOrder(e) {
      // console.log(e.currentTarget.dataset.jump)
     
      let vm = this
      if (!vm.data.isAuth) {
         return wx.navigateTo({
            url: '/pages/authorization/authorization',
         })
      } else {
         if (this.data.click_time == 0) {
            var that = this;
            // 创建一个动画实例
            var animation = wx.createAnimation({
               // 动画持续时间
               duration: 500,
               // 定义动画效果，当前是匀速
               timingFunction: 'linear'
            })
            // 将该变量赋值给当前动画
            that.animation = animation
            // 先在y轴偏移，然后用step()完成一个动画
            animation.translateY(200).step()
            // 用setData改变当前动画
            that.setData({
               // 通过export()方法导出数据
               animationData: animation.export(),
               // 改变view里面的Wx：if
               chooseSize1: true,
               click_time: 1,

            })
            // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
            setTimeout(function () {
               animation.translateY(0).step()
               that.setData({
                  animationData: animation.export()
               })
            }, 200)

         } else {            
            if (this.data.dataInfo.schedule_type == 1) {
               // 成品
               wx.navigateTo({
                  url: '/pages/order/orderwrite/orderwrite?id=' + this.data.proid + "&timeable_id=" + this.data.priceTime,
               })
            } else {
               // 预售
               wx.navigateTo({
                  url: '/pages/order/orderwrite/orderwrite?id=' + this.data.proid + "&timeable_id=" + this.data.priceTime,
               })
            }          
         }
      }
   },
   requestAuch() {
      let vm = this
      AJAX("member/auth").then(res => {
        
         vm.setData({
            isAuth: res.data.auth
         })
      })
   },
   navBack() {
      
      
      if (this.data.share_member_id == 0) {
         wx.navigateBack()
      } else {
         wx.switchTab({
            url: '/pages/index/index',
         })
      }

   },
   // 监听srcollview滚动
   srcollTap(e) {     
     console.log(e)
   
      if (e.detail.scrollTop > 240) {
         this.setData({
            tabPosition: true,
            floorstatus: true
         })
      } else {
         this.setData({
            tabPosition: false,
            floorstatus: false
         })
      }
   },
 
   goTop: function (e) {  // 一键回到顶部    
      this.setData({
         scrolltop: this.data.scrolltop = 0
      });

     
   },
   colTap(e) {
      let vm = this
      let _val = e.currentTarget.dataset.col == 1 ? 0 : 1
      AJAX("member-collection/execute", "POST", {
         product_id: vm.data.proid,
         execute_type: _val
      }).then(res => {
         wx.showToast({
            title: _val ? "收藏成功" : "取消收藏成功",
            icon: "none"
         })
         vm.requestInfo()
      })
   },
   codeRead(e) {
      let _url = e.currentTarget.dataset.url
      if (!_url) {
         return
      }
      wx.previewImage({
         urls: [_url],
      })
      // wx.getImageInfo({// 获取图片信息（此处可不要）
      //   src: _url,
      //   success: function (res) {
      //     debugger
      //   }
      // })
   }, 



})